from fileOperate import loadFromFileRaw
import json

class Config():
    _path = "" # eg: /home/Zecyel/config.json
    _mp = {}
    autoSave = False # 如果调用 _mp 中值的方法就没法自动保存了
    makeBackup = False
    # Warning: autoSave = makeBackup = True may cause low-running-speed

    def __init__(self, path = None):
        self._path = path

    def load(self, path):
        self._path = path
        stt, tmp = loadFromFileRaw(path)
        assert stt
        self._mp = json.loads(tmp)
    
    def reload(self):
        self.load(self._path)
        print("Reloaded")

    def __delitem__(self, key):
        if isinstance(key, int):
            key = str(key)
        self._mp.pop(key)
        if self.autoSave:
            self.save()

    def __setitem__(self, key, value):
        if isinstance(key, int):
            key = str(key)
        self._mp[key] = value
        if self.autoSave:
            self.save()

    def __getitem__(self, key):
        if isinstance(key, int):
            key = str(key)
        return self._mp[key]
    
    def __contains__(self, key):
        if isinstance(key, int):
            key = str(key)
        return key in self._mp

    def save(self):
        pos = self.path.rindex("/") + 1
        binDir = self.path[:pos]
        posDot = self.path.rindex(".")
        filename = self.path[pos: posDot]
        post = self.path[posDot + 1:]
        if self.makeBackup:
            moveFile(self.path, binDir + "backup/" + filename + "." + timeStamp() + "." + post)
        writeToFile(self.path, json.dumps(self._mp))

# global config

globalConf = Config()
globalConf.load("@/config/global.json")
missionConf = Config()
missionConf.load("@/config/mission.json")